package com.nur.dal;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class Conexion extends SQLiteOpenHelper{

	private static final String NOMBREDB = "noteichon.db";
	private static final int VERSION = 1;
	
	private static Conexion instance;
	
	private Conexion(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}
	
	private Conexion(Context context){
		super(context, NOMBREDB, null, VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE nota "
				+ "  ( "
				+ "     idnota      INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
//				+ "     idusuario   INTEGER NOT NULL, "
				+ "     comentario  TEXT, "
				+ "     hora_inicio TEXT, "
				+ "     hora_fin    TEXT, "
				+ "     fecha       TEXT, "
				+ "     tipo        TEXT, "
				+ "     nuevo       INTEGER "
				+ "  );"

				+ "CREATE TABLE usuario "
				+ "  ( "
				+ "     idusuario    INTEGER PRIMARY KEY AUTOINCREMENT, "
				+ "     login        TEXT, "
				+ "     fecha_creado TEXT "
				+ "  );"
				
				+ "CREATE TABLE backup "
				+ "  ( "
				+ "     idbackup     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "
		//		+ "     idusuario    INTEGER, "
				+ "     fecha_creado TEXT "
				+ "  );"

				+ "CREATE TABLE backupcontenido "
				+ "  ( "
				+ "     idbackup    INTEGER NOT NULL AUTOINCREMENT, "
				+ "     idnota      INTEGER, "
				+ "     comentario  TEXT, "
				+ "     hora_inicio TEXT, "
				+ "     hora_fin    TEXT, "
				+ "     fecha       TEXT, "
				+ "     tipo        TEXT "
				+ "  );"

				+ "ALTER TABLE nota "
				+ "  ADD FOREIGN KEY (idusuario) REFERENCES usuario (idusuario);"

				+ "ALTER TABLE backup "
				+ "  ADD FOREIGN KEY (idusuario) REFERENCES usuario (idusuario);"

				+ "ALTER TABLE backupcontenido "
				+ "  ADD FOREIGN KEY (idbackup) REFERENCES backup (idbackup);");

		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		/*db.execSQL("DROP TABLE IF EXISTS usuario;");
		onCreate(db);*/
		
	}
	
	public static Conexion getInstance(){
		return instance;
	}
	
	public static void initInstance(Context context){
		if(instance == null)
			instance = new Conexion(context);
	}
}
